package cn.iocoder.yudao.module.promotion.redpacket.mq;

import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.module.api.trade.order.dto.TradeOrderRespDTO;
import cn.iocoder.yudao.module.api.trade.order.message.TradeOrderCompletedMessage;
import cn.iocoder.yudao.module.api.trade.scan.dto.ScanOrderDTO;
import cn.iocoder.yudao.module.api.trade.scan.message.ScanOrderPaidMessage;
import cn.iocoder.yudao.module.promotion.redpacket.service.core.CoreRedPacketRecordService;
import cn.iocoder.yudao.module.promotion.redpacket.service.core.CoreRedPacketUsedService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 店铺红包 事件消费者
 *
 * @author 山野羡民
 */
@Component
@Slf4j
public class RedPacketConsumer {

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(ScanOrderPaidMessage message) {
        ScanOrderDTO order = message.getOrder();
        log.info("[promotion/redpacket][onMessage][扫码订单付款完成事件({})]", order.getTradeNo());
        SpringUtil.getBean(CoreRedPacketUsedService.class).useRedPacketIfNecessary(order);
        boolean firstOrderRedPacket = SpringUtil.getBean(CoreRedPacketRecordService.class).grantFirstOrderRedPacketIfNecessary(order);
        if (!firstOrderRedPacket) {
            SpringUtil.getBean(CoreRedPacketRecordService.class).grantEveryConsumeRedPacketIfNecessary(order);
        }
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(TradeOrderCompletedMessage message) {
        TradeOrderRespDTO order = message.getOrder();
        Assertions.notNull(order, "交易订单完成事件携带的订单信息为空");
        log.info("[promotion/redpacket][onMessage][交易订单完成事件({})]", order.getNo());
        SpringUtil.getBean(CoreRedPacketRecordService.class).grantEveryConsumeRedPacketIfNecessary(order);
    }

}
